﻿using Seagull.BarTender.Print;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 通过Bartender模块打印标签
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            // 这里简化了例子用一个List代替,实际是通过Excel表格导入.在DataGridView显示数据,批量打印
            List<Test> list = new List<Test>() 
            {
                new Test(){ QRCodeText="姓名:李四\r\n年龄:18",Address="浙江金华1" },
                new Test(){ QRCodeText="姓名:王五\r\n年龄:22",Address="浙江金华2" },
                new Test(){ QRCodeText="17734567749858",Address="浙江金华3" }
            };

            //创建打印机对话框
            PrintDialog printDialog = new PrintDialog();

            // 如果用户选择打印机
            if (printDialog.ShowDialog() == DialogResult.OK)
            {
                // 获取用户选择打印机名称
                string printName = printDialog.PrinterSettings.PrinterName;

                // 创建打印引擎实例

                Engine engine = new Engine();

                engine.Start();

                foreach (Test test in list )
                {
                    

                    // 打开标签模板文件
                    LabelFormatDocument doc = engine.Documents.Open(Application.StartupPath + Path.DirectorySeparatorChar + @"\template\测试标签.btw");

                    // 设置标签文本,二维码等参数 参数:MyRQCode,MyAddress模板字段名称
                    doc.SubStrings["MyQrCode"].Value = test.QRCodeText;
                    doc.SubStrings["MyAddress"].Value = test.Address;

                    // 打印标签,将打印机名称传进去
                    doc.Print(printName);

                    // 关闭标签文件
                    // SaveOptions.SaveChanges,会将设置的字段数据保存到模版
                    //doc.Close(SaveOptions.SaveChanges);
                    // 这里使用不保存到模版
                    doc.Close(SaveOptions.DoNotSaveChanges);
                  
                }

                // 关闭打印引擎
                engine.Stop();

            }

        }
    }

    class Test
    {
        public String QRCodeText { get; set; }
        public String Address { get; set; }
    }

}
